-- Copyright (c) 2024 Huawei Technologies Co., Ltd.
-- openUBMC is licensed under Mulan PSL v2.
-- You can use this software according to the terms and conditions of the Mulan PSL v2.
-- You may obtain a copy of Mulan PSL v2 at:
--         http://license.coscl.org.cn/MulanPSL2
-- THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
-- EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
-- MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
-- See the Mulan PSL v2 for more details.

-- Description: 管理策略重配的标准文件
local class = require 'mc.class'
local singleton = require 'mc.singleton'
local json = require 'cjson'
local log = require 'mc.logging'
local policy_registery = require 'domain.policy_config.policy_registery'
local imu = require 'infrastructure.imu'
local base_messages = require 'messages.base'
local bios_factory = require 'factory.bios_factory'

local PolicyConfigTransfer = class()

function PolicyConfigTransfer:ctor()
end

function PolicyConfigTransfer:fill_prop(ipmi_format_tbl, config_data, system_id)
    local ok, current_json = pcall(function()
        local bios_ser = bios_factory.get_service('bios_service')
        local data = bios_ser:get_config_data('PolicyConfigJson', system_id)
        return json.decode(data)
    end)
    if not ok then
        log:error('[bios]policy transform: parse current config val fail')
        error({Code = base_messages.ActionNotSupported('policy config')})
    end
    for _, v in pairs(ipmi_format_tbl) do
        v:set_data(config_data, current_json)
    end
end

-- 1、校验配置合法性
-- 2、转换为ipmi
-- 3、填充ipmi数据:非关键字的属性，如果用户配置则使用用户的配置，否则使用current
function PolicyConfigTransfer:transform(config_data, system_id)
    if not config_data then
        log:error('[bios]policy transform: config data invalid')
        error({Code = base_messages.MalformedJSON()})
    end
    local registery = policy_registery.new(system_id)
    local ipmi_format_tbl = registery:build_ipmi(config_data)
    self:fill_prop(ipmi_format_tbl, config_data, system_id)
    return ipmi_format_tbl
end

-- 对外接口
function PolicyConfigTransfer:send(content, system_id)
    local ok, user_json = pcall(json.decode, content)
    if not ok then
        log:error('[bios]policy transform: content invalid')
        error({Code = base_messages.MalformedJSON()})
    end
    local config_data = user_json.Attributes
    local ipmi_format_tbl = self:transform(config_data, system_id)
    local imu_cmd = imu.get_instance()
    for _, v in pairs(ipmi_format_tbl) do
        imu_cmd:send(v:generate_ipmi_msg(system_id))
    end
    local bios_ser = bios_factory.get_service('bios_service')
    bios_ser:update_user_data(system_id, config_data)
end

return singleton(PolicyConfigTransfer)